<template>
  <div
    style="
      border-radius: 20px;
      background-color: rgba(255, 255, 255, 0.5);
      padding: 30px;
      border: 1px solid rbga(0, 0, 0, 0.2);
      overflow: hidden;
      box-shadow: 0px 0px 13px 13px rgba(0, 0, 0, 0.5);
    "
  >
    <!-- 显示系统标题或者是图片logo -->
    <!-- <LoginFormTitle v-show="getShow" class="enter-x" /> -->
    <img :src="getLoginLogoImage" class="loginLogoImage" />
    <!-- <img v-if="projectCode === 'yzh'" class="logoImage-yzh" /> -->
    <!-- <img v-else-if="projectCode === 'ky'" class="logoImage-ky" /> -->
    <!-- <img v-else class="logoImage-qc" /> -->
    <Form
      class="p-4 enter-x"
      :model="formData"
      :rules="getFormRules"
      ref="formRef"
      v-show="getShow"
      @keypress.enter="handleLogin"
    >
      <FormItem name="account" class="enter-x">
        <Input
          size="large"
          v-model:value="formData.account"
          :placeholder="t('sys.login.userName')"
          class="fix-auto-fill"
        />
      </FormItem>

      <!-- 必须使用v-model:value，不然无法实现双向绑定 -->
      <FormItem name="password" class="enter-x">
        <InputPassword
          size="large"
          visibilityToggle
          v-model:value="formData.password"
          :placeholder="t('sys.login.password')"
        />
      </FormItem>

      <ARow class="enter-x">
        <ACol :span="12">
          <FormItem>
            <!-- No logic, you need to deal with it yourself -->
            <Checkbox v-model:checked="rememberMe" size="small">
              {{ t('sys.login.rememberMe') }}
            </Checkbox>
          </FormItem>
        </ACol>
        <ACol :span="12">
          <FormItem :style="{ 'text-align': 'right' }">
            <!-- No logic, you need to deal with it yourself -->
            <!-- <Button type="link" size="small" @click="setLoginState(LoginStateEnum.RESET_PASSWORD)">
            {{ t('sys.login.forgetPassword') }}
          </Button> -->
          </FormItem>
        </ACol>
      </ARow>

      <!-- 登录按钮 -->
      <FormItem class="enter-x">
        <Button type="primary" size="large" block @click="handleLogin" :loading="loading">
          {{ t('sys.login.loginButton') }}
        </Button>
        <!-- <Button size="large" class="mt-4 enter-x" block @click="handleRegister">
        {{ t('sys.login.registerButton') }}
      </Button> -->
      </FormItem>
      <!-- <ARow class="enter-x">
      <ACol :md="8" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.MOBILE)">
          {{ t('sys.login.mobileSignInFormTitle') }}
        </Button>
      </ACol>
      <ACol :md="8" :xs="24" class="!my-2 !md:my-0 xs:mx-0 md:mx-2">
        <Button block @click="setLoginState(LoginStateEnum.QR_CODE)">
          {{ t('sys.login.qrSignInFormTitle') }}
        </Button>
      </ACol>
      <ACol :md="7" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.REGISTER)">
          {{ t('sys.login.registerButton') }}
        </Button>
      </ACol>
    </ARow> -->

      <!-- <Divider class="enter-x">{{ t('sys.login.otherSignIn') }}</Divider> -->
      <!-- <Divider class="enter-x" style="font-size: 0.6rem">{{ t('sys.support') }}</Divider> -->
      <Divider class="enter-x" style="font-size: 0.6rem">{{ getAppCopyright }}</Divider>
      <!-- <div class="flex justify-evenly enter-x" :class="`${prefixCls}-sign-in-way`">
      <GithubFilled />
      <WechatFilled />
      <AlipayCircleFilled />
      <GoogleCircleFilled />
      <TwitterCircleFilled />
    </div> -->
    </Form>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, ref, unref, computed } from 'vue';

  import { useRouter } from 'vue-router';
  import { useGo } from '/@/hooks/web/usePage';
  import { refreshBlackList } from '/@/api/platform/blackList';
  import { Checkbox, Form, Input, Row, Col, Button, Divider } from 'ant-design-vue';
  // import {
  //   GithubFilled,
  //   WechatFilled,
  //   AlipayCircleFilled,
  //   GoogleCircleFilled,
  //   TwitterCircleFilled,
  // } from '@ant-design/icons-vue';
  import LoginFormTitle from './LoginFormTitle.vue';

  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { useUserStore } from '/@/store/modules/user';
  import { LoginStateEnum, useLoginState, useFormRules, useFormValid } from './useLogin';
  import { useDesign } from '/@/hooks/web/useDesign';
  //import { onKeyStroke } from '@vueuse/core';
  //默认的登录logo图片
  import defaultLoginLogoImage from '/images/logo-qc-login.png';

  import { qcLoginPasswordEncrypt } from '/@/utils/cipher';

  import { useGlobSetting } from '/@/hooks/setting';
  const { globalProjectCode } = useGlobSetting();

  const ACol = Col;
  const ARow = Row;
  const FormItem = Form.Item;
  const InputPassword = Input.Password; // ant-design-vue的密码输入框
  const { t } = useI18n();
  const { notification, createErrorModal, createWarningModal } = useMessage();
  const { prefixCls } = useDesign('login');
  const userStore = useUserStore();
  const router = useRouter();
  const go = useGo();

  // const { setLoginState, getLoginState } = useLoginState();
  const { getLoginState } = useLoginState();
  const { getFormRules } = useFormRules();

  const formRef = ref();
  const loading = ref(false);
  const rememberMe = ref(false);
  const projectCode = ref<String>('');

  //获取登录传入的项目编码：先从store中获取，如果没有再使用env文件中的
  let storeProjectCode = userStore.getUserCurrentProjectCode;
  console.log(
    'LoginForm.vue storeProjectCode=' +
      storeProjectCode +
      ' env globalProjectCode=' +
      globalProjectCode,
  );
  let resultProjectCode = globalProjectCode;
  if (storeProjectCode != undefined && storeProjectCode != null && storeProjectCode != '')
    resultProjectCode = storeProjectCode;
  projectCode.value = resultProjectCode;

  const formData = reactive({
    account: '',
    password: '',
  });

  const { validForm } = useFormValid(formRef);

  //onKeyStroke('Enter', handleLogin);

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);

  /**
   * 获取登录logo图片，先从store中存储的当前项目logo图片获取，如果没有使用默认
   */
  const getLoginLogoImage = computed(() => {
    const currentProject = userStore.getUserCurrentProject;
    if (currentProject != undefined && currentProject != null) {
      //取store中当前项目信息的values，按对象方式取值
      if (currentProject.values != undefined && currentProject.values != null) {
        let loginlogo = currentProject.values.loginlogo;
        if (loginlogo != undefined && loginlogo != null && loginlogo != '') return loginlogo;
      }
    }
    //如果没有设置登录logo，默认使用渠成登录logo图片
    return defaultLoginLogoImage;
  });

  /**
   * 获取APP版权信息
   */
  const getAppCopyright = computed(() => {
    let copyright = t('sys.support');
    const currentProject = userStore.getUserCurrentProject;
    console.log('LoginForm.vue getAppCopyright currentProject', currentProject);
    if (currentProject != undefined && currentProject != null) {
      //取store中当前项目信息的values，按对象方式取值
      if (currentProject.values != undefined && currentProject.values != null) {
        let copyrightValue = currentProject.values.copyright;
        // copyrightValue = currentProject.values["copyright"];
        if (copyrightValue != undefined && copyrightValue != null && copyrightValue != '')
          copyright = copyrightValue;
      }
    }
    return copyright;
  });

  // 登录按钮方法
  async function handleLogin() {
    const data = await validForm();
    if (!data) return;
    try {
      loading.value = true;
      //获取客户端类型
      const ua = navigator.userAgent;
      const isIPhone = /(iPhone|iPad|iPod|iOS)/i.test(ua);
      const isAndroid = /(Android)/i.test(ua);
      let ctype = 10;
      if (isIPhone || isAndroid) ctype = 20;

      //如果用作测试，在此固定赋值
      //阳宗海网站定义--登录使用的默认项目编码
      // project: 'yzh',
      //开远网站定义--登录使用的默认项目编码
      // project: 'ky',
      //渠成系统定义--登录使用的默认项目编码
      // project: 'qcweb',

      const loginResult = await userStore.qclogin({
        vtype: 1,
        ctype: ctype,
        // cinfo: ua,//客户端信息在api中从request的header中获取
        code: data.account,
        pwd: qcLoginPasswordEncrypt(data.password),
        project: projectCode.value,
        mode: 'none', //不要默认的错误提示
      });

      if (
        (loginResult.hasOwnProperty('sucess') == true && loginResult.sucess == true) ||
        (loginResult.hasOwnProperty('success') == true && loginResult.success == true)
      ) {
        //登录成功，设置token
        if (
          loginResult.token != undefined &&
          loginResult.token != null &&
          loginResult.token != ''
        ) {
          userStore.setToken(loginResult.token);
        }
        //获取用户的项目列表和当前项目信息
        userStore.setUserValidProjects(loginResult.projects);
        if (
          loginResult.projectcode != undefined &&
          loginResult.projectcode != null &&
          loginResult.projectcode != ''
        ) {
          userStore.setUserCurrentProjectCode(loginResult.projectcode);
          //设置store中的用户当前项目信息
          if (loginResult.projects && loginResult.projects.length > 0x0) {
            loginResult.projects.forEach((element) => {
              //参数值使用统一类型返回，其中的项目编码对应的属性为objcode
              if (element.objcode === loginResult.projectcode) {
                userStore.setUserCurrentProject(element);
              }
            });
          }
        } else {
          userStore.setUserCurrentProject(null);
        }
        //将提示信息放在store中，在跳转后的页面中获取进行处理；如果为空也需要进行赋值对store进行更新
        userStore.setLoginPrompt(loginResult.prompt);
        //测试获取store中的token
        console.log('login success get store token', userStore.getToken);

        //如果有提示信息（可能为修改密码或系统通知），显示提示信息
        if (!loginResult.prompt) {
          //登录成功，并且没有任何提示信息；显示登录成功信息，并进行相应的路由跳转
          notification.success({
            message: t('sys.login.loginSuccessTitle'),
            description: `${t('sys.login.loginSuccessDesc')}: ${loginResult.name}`,
            duration: 3,
          });

          //登录成功后页面跳转
          loginSuccessRedirect();
        } else {
          //登录成功，但有提示信息；如果有提示信息（需要在登录时进行显示的）说明不需要进到首页或者需要用户操作后进行相应跳转
          createWarningModal({
            title: t('sys.login.loginSuccessTitle'),
            content: `${loginResult.prompt}`,
            getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
            onOk: () => {
              //提示信息框显示后点击确定按钮的处理
              loginSuccessRedirect();
            },
          });
        }
      } else {
        //登录失败，清除store
        userStore.setToken(undefined);
        userStore.setUserValidProjects(null);
        //2024-3-13，修改为：登录失败不清除store中的用户当前项目和项目编码；
        //清除后如果跳转回登录界面没有项目编码使用env中的项目编码会导致用户与所在项目信息不匹配无法登录;
        // userStore.setUserCurrentProject(null);
        // userStore.setUserCurrentProjectCode(undefined);
        userStore.setUserInfo(null);

        createErrorModal({
          title: t('sys.api.errorTip'),
          content: t('sys.login.loginFailTitle') + loginResult.prompt,
          getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
        });
      }
      if (
        loginResult.hasOwnProperty('refreshgateway') === true &&
        loginResult.refreshgateway === true
      ) {
        refreshBlackList().then((res) => {
          if (!res) {
            console.log('blacklist reload success');
          } else {
            console.log('error');
          }
        });
      }
    } catch (error) {
      createErrorModal({
        title: t('sys.api.errorTip'),
        content: (error as unknown as Error).message || t('sys.api.networkExceptionMsg'),
        getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
      });
    } finally {
      loading.value = false;
    }
  }

  /**
   * 成功成功后跳转
   */
  function loginSuccessRedirect() {
    //获取路由跳转信息中的redirect，如果有指定redirect跳转到指定路由，如果没有指定跳转到默认首页
    let goHome: boolean = true;
    let redirectRouter: string = '';
    console.log('LoginForm handleLogin router', router.currentRoute.value);
    if (router.currentRoute.value.query.redirect) {
      console.log(
        'LoginForm handleLogin router redirect',
        router.currentRoute.value.query.redirect,
      );
      let redirect = router.currentRoute.value.query.redirect;
      // console.log('typeof redirect', typeof redirect);
      if (typeof redirect == 'string') {
        // go(redirect as string);
        goHome = false;
        redirectRouter = redirect;
      }
    }
    userStore.afterLoginAction(goHome, redirectRouter);
  }
</script>
<style scoped lang="less">
  .logoImage-yzh {
    @apply h-full max-h-16 mb-4;

    // content: url('../../../../images/logo-ceic.webp');//build后路径不对
    //阳宗海网站定义--登录页面logo
    content: url('/@/../images/logo-yzh.png');
    object-fit: scale-down;
  }
  .logoImage-ky {
    @apply h-full max-h-16 mb-4;

    // content: url('../../../../images/logo-ceic.webp');//build后路径不对
    //开远网站定义--登录页面logo
    content: url('/images/logo-ky.png');
    object-fit: scale-down;
  }
  .logoImage-qc {
    @apply h-full max-h-16 mb-4;

    // content: url('../../../../images/logo-ceic.webp');//build后路径不对
    //渠成系统定义--登录页面logo
    content: url('/@/../images/logo-qc-login.png');
    object-fit: scale-down;
  }
  .loginLogoImage {
    @apply h-full max-h-16 mb-4;
    object-fit: scale-down;
  }
</style>
